package cn.fintecher.pangolin.service.report.scheduled;

import cn.fintecher.pangolin.common.enums.UserStatus;
import cn.fintecher.pangolin.common.utils.RepositoryUtil;
import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.entity.elastic.BehavioralProcess;
import cn.fintecher.pangolin.entity.mysql.QUser;
import cn.fintecher.pangolin.entity.mysql.User;
import cn.fintecher.pangolin.service.report.elastic.BehavioralProcessElastic;
import cn.fintecher.pangolin.service.report.repository.UserRepository;
import cn.fintecher.pangolin.service.report.task.BehavioralProcessTask;
import org.apache.commons.collections4.IterableUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Auther: xiaqun
 * @Description: 行为过程监控调度
 * @Date: 13:56 2019/12/10
 */

@EnableScheduling
@Component
public class BehavioralProcessScheduled {
    private static final Logger log = LoggerFactory.getLogger(BehavioralProcessScheduled.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BehavioralProcessTask behavioralProcessTask;

    @Autowired
    private BehavioralProcessElastic behavioralProcessElastic;

    /**
     * 生成行为过程监控报表历史数据
     */
    @Scheduled(cron = "00 50 23 * * ?")
    public void generateReport() {
        log.info("生成行为过程监控报表历史数据开始,{}", ZWDateUtil.getNowDateTime());
        Iterable<User> iterable = userRepository.findAll(QUser.user.status.ne(UserStatus.LEAVE));
        List<User> users = IterableUtils.toList(iterable);
        List<CompletableFuture<BehavioralProcess>> list = new ArrayList<>();
        Date date = ZWDateUtil.getNowDate();
        for (User user : users) {
            CompletableFuture<BehavioralProcess> future = behavioralProcessTask.doTask(user, date);
            list.add(future);
        }
        try {
            List<BehavioralProcess> processList = new ArrayList<>();
            for (CompletableFuture<BehavioralProcess> future : list) {
                processList.add(future.get());
            }
            RepositoryUtil.saveData(behavioralProcessElastic, processList);
            log.info("生成行为过程监控报表历史数据结束,{}", ZWDateUtil.getNowDateTime());
        } catch (InterruptedException | ExecutionException e) {
            log.info(e.getMessage(), e);
            log.info("生成行为过程监控报表历史数据失败");
        }
    }
}
